﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using FinalOpdracht.Filters;
using FinalOpdracht.Models;


namespace FinalOpdracht.Controllers
{
    [InitializeSimpleMembership]
    public class HomeController : Controller
    {
        private BlogContext db = new BlogContext();
        private UsersContext UserDb = new UsersContext();

        public ActionResult Index()
        {
            return View(db.Blogs.ToList());
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpGet]
        public ActionResult NewRole()
        {
            UserDb.UserProfiles.ToList();

            ViewBag.AllRoles = new List<string>(Roles.GetAllRoles().ToList());
            //ViewBag.GetRolesForUser = new List<string>(Roles.GetRolesForUser("Bastiaan").ToList());

            return View(UserDb.UserProfiles.ToList());
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult NewRole(string RoleName, string DeleteRole)
        {
            RoleName = Request["NewRole"];
            if (RoleName != null && RoleName != "" && !Roles.RoleExists(RoleName))
            {
                Roles.CreateRole(RoleName);
            }

            DeleteRole = Request["role"];
            if (DeleteRole != null && DeleteRole != "" && Roles.RoleExists(DeleteRole))
            {
                Roles.DeleteRole(DeleteRole);
            }

            return RedirectToAction("NewRole");
        }

        [Authorize(Roles = "Admin")]
        [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            UserProfile User = UserDb.UserProfiles.Find(id);

            ViewBag.AllRoles = new List<string>(Roles.GetAllRoles().ToList());
            ViewBag.ShowUserRoles = new SelectList(Roles.GetRolesForUser(User.UserName));
            ViewBag.SelectRoleList = new SelectList(Roles.GetAllRoles().Except(Roles.GetRolesForUser(User.UserName)));

            return View(User);
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult Edit(string userName, string roleName, string DeleteUserRole)
        {
            userName = Request["UserName"];
            roleName = Request["SelectRoleList"];
            DeleteUserRole = Request["ShowUserRoles"];

            if (roleName != null && roleName != "")
            {
                Roles.AddUserToRole(userName, roleName);
            }

            if (DeleteUserRole != null && DeleteUserRole != "")
            {
                Roles.RemoveUserFromRole(userName, DeleteUserRole);
            }
            return RedirectToAction("NewRole");
        }

    }
}